<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\helpers\traits\SearchDataForModel;
use app\model\Sample as SampleModel;
use app\model\Community;
use app\model\SampleCommunityPivot;
use app\model\SampleProjectTargetPivot;
use think\Request;

class Sample extends BaseController
{
    use SearchDataForModel;

    /**
     * @User: 刘海龙
     * @Date: 2021/7/26
     * @Time: 16:49
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 根据项目id获取对应的样本点
     */
    public function getSampleList()
    {
        $limit = $this->request->param('limit', 0);
        $map = [];
        if ($this->request->has('project_id') && !empty($this->request->param('project_id'))) {
            $map[] = ['review_project_id', '=', $this->request->param('project_id')];
        }
        $res = $this->search(new SampleModel(), $map, $limit, 'desc', ['project', 'children','communities','targets']);
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/7/26
     * @Time: 16:39
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 分配社区和项目指标
     */
    public function saveAllotCommunity()
    {
        $data = $this->request->param();
        $sample = SampleModel::find($data['sample_id']);
        $community = Community::find($data['community_id']);
        $project_target = Community::find($data['project_target_id']);
        if (is_null($sample) && is_null($community) && is_null($project_target)) {
            return $this->response(403, '暂未找到该样本点或社区点或项目指标');
        }
        SampleCommunityPivot::sampleCommunitySave($sample,$data['community_id']);
        SampleProjectTargetPivot::sampleProjectTargetSave($sample,$data['project_target_id']);
        return $this->response();

    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/16
     * @Time: 8:40
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除样本点
     */
    public function delSample($id){
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            $data = SampleModel::find($id);
            if (is_null($data)) {
                return $this->response(404, '该样本点不存在');
            }
            $data->delete();
        }
        return $this->response();
    }
}
